let isLoading = false

// 加解密处理
async function handleEncrypt() {
    if (isLoading) return
    isLoading = true
    updateUIState()

    try {
        const plaintext = document.getElementById('plaintext').value
        const key = document.getElementById('key').value

        if (!validateInput(plaintext, key)) return

        const {result, error} = await window.electronAPI.encrypt({plaintext, key})
        handleResult(result, error, 'ciphertext')
    } catch (error) {
        showError('加密失败: ' + error.message)
    } finally {
        isLoading = false
        updateUIState()
    }
}

async function handleDecrypt() {
    if (isLoading) return
    isLoading = true
    updateUIState()

    try {
        const ciphertext = document.getElementById('ciphertext').value
        const key = document.getElementById('key').value

        if (!validateInput(ciphertext, key)) return

        const {result, error} = await window.electronAPI.decrypt({ciphertext, key})
        handleResult(result, error, 'plaintext')
    } catch (error) {
        showError('解密失败: ' + error.message)
    } finally {
        isLoading = false
        updateUIState()
    }
}

// 辅助函数
function validateInput(text, key) {
    if (!text.trim()) {
        showError('内容不能为空')
        return false
    }
    if (!key) {
        showError('请输入密钥')
        return false
    }
    return true
}

function handleResult(result, error, targetId) {
    if (error) {
        showError(error)
    } else {
        document.getElementById(targetId).value = result
        showError('')
        autoFormatIfJSON(targetId)
    }
}

function updateUIState() {
    document.querySelectorAll('.btn').forEach(btn => {
        btn.disabled = isLoading
        btn.style.opacity = isLoading ? 0.7 : 1
    })
    document.getElementById('errorMessage').textContent = isLoading ? '处理中...' : ''
}

// JSON处理功能
function formatJSON(textareaId) {
    const textarea = document.getElementById(textareaId)
    try {
        const formatted = JSON.stringify(JSON.parse(textarea.value), null, 2)
        textarea.value = formatted
        updateJSONStatus(textarea, true)
    } catch (error) {
        updateJSONStatus(textarea, false)
        showError('无效的JSON格式')
    }
}

function autoFormatIfJSON(textareaId) {
    const textarea = document.getElementById(textareaId)
    if (isValidJSON(textarea.value)) {
        formatJSON(textareaId)
    }
}

function isValidJSON(str) {
    try {
        JSON.parse(str)
        return true
    } catch (e) {
        return false
    }
}

function updateJSONStatus(textarea, isValid) {
    const container = textarea.parentElement.parentElement
    const statusElem = container.querySelector('.json-status') || createJSONStatusElement(container)
    statusElem.textContent = isValid ? 'Valid JSON' : 'Invalid JSON'
    statusElem.style.color = isValid ? '#2ed573' : '#ff4757'
}

function createJSONStatusElement(container) {
    const elem = document.createElement('div')
    elem.className = 'json-status'
    container.appendChild(elem)
    return elem
}

// 错误处理
function showError(message) {
    const elem = document.getElementById('errorMessage')
    elem.textContent = message
    elem.style.color = message ? '#ff4757' : 'transparent'
}

// 实时密钥验证
document.getElementById('key').addEventListener('input', function (e) {
    const keyLength = new TextEncoder().encode(e.target.value).length
    e.target.style.borderColor = [16, 24, 32].includes(keyLength) ? '#2ed573' : '#ff4757'
})

// 快捷键支持
document.addEventListener('keydown', (e) => {
    if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
        const active = document.activeElement
        if (active.classList.contains('code-area')) {
            formatJSON(active.id)
        }
    }
})

// 自动检测JSON
document.querySelectorAll('.code-area').forEach(textarea => {
    textarea.addEventListener('input', function () {
        updateJSONStatus(this, isValidJSON(this.value))
    })
})
